package com.yztstudy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yztstudy.dto.Result;
import com.yztstudy.entity.ShopType;
import com.yztstudy.mapper.ShopTypeMapper;
import com.yztstudy.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yztstudy.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * TODO 查询所有的店铺类型
     * @return 商铺类型详情数据
     */
    @Override
    public Result queryAllTypes() {

        // TODO 1.先从redis中查询店铺类型是否存在
        List<String> cacheShopTypes = stringRedisTemplate.opsForList().range(RedisConstants.SHOP_TYPE_KEY, 0, -1);
        List<ShopType> allShopTypes = new ArrayList<>();


        // TODO 2.判断是否存在，存在就直接返回
        if (cacheShopTypes != null && cacheShopTypes.size() > 0)
        {
            allShopTypes = JSONUtil.toList(cacheShopTypes.toString(), ShopType.class);
            return Result.ok(allShopTypes);
        }

        // TODO 3.不存在就从数据库查询
        allShopTypes = query().orderByAsc("sort").list();

        // TODO 4.如果数据库也不存在，就返回错误
        if (allShopTypes == null || allShopTypes.size() == 0)
        {
            return Result.fail("店铺类型为空!");
        }

        // TODO 5.存在就写入redis，同时给前端
        for (ShopType shopType : allShopTypes)
        {
            stringRedisTemplate.opsForList().rightPush(RedisConstants.SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.expire(RedisConstants.SHOP_TYPE_KEY, RedisConstants.SHOP_TYPE_TTL, TimeUnit.MINUTES); //设置过期时间

        return Result.ok(allShopTypes);
    }
}
